# -*- coding: utf-8 -*-
import hashlib
import json
import urllib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

# 商户名称：燊雨资产管理（上海）有限公司
# 商户编号：MD201807270000000286 
# 登录号：UD201807270000031817 
# 登录密码：123456 支付密码默认：123456 
# MD5秘钥：TByc8wqsvM2bqZPrtssOyYEhJII9z1tc 
# 工作密钥：1sj90BBBwhQfH0yR1hgWh77QN6acDHSj
# 到账方式：非结算到卡，清算到平台虚拟户
# 商户平台：http: // www.bcahzp.com / 
# 生产接口地址：http: // www.bcahzp.com / paygateway / gateway / api / pay
APP_CONF = {
    'MD201807270000000286': {  # dwc 10~5000 支付宝
        'API_KEY': 'TByc8wqsvM2bqZPrtssOyYEhJII9z1tc',
        'gateway': 'http://www.bcahzp.com/paygateway/gateway/api/pay',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'Key=%s' % key
    _LOGGER.info("renrenpay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['Sign']
    params.pop('Sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("renrenpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 0202-网银支付
# 0203-微信扫码
# 0208-快捷支付h5版
# 0209-微信WAP
# 0210-支付宝WAP
# 0212-QQ钱包WAP
# 0217-QQ钱包扫码
# 0218-银联在线
# 0219-银联扫码
# 0222-认证支付(银联快捷)
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '0209'
    elif service == 'alipay':
        payType = '0210'
    elif service == 'qq':
        payType = '0212'
    elif service == 'quick':
        payType = '0208'
    else:
        payType = '0210'
    return payType


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('TradeType', 'bis.pay.submit'),
        ('OperatorID', app_id),
        ('PayType', _get_pay_type(service)),
        ('MemberID', pay.user_id),
        ('MerchantID', app_id),
        ('OrderID', str(pay.id)),
        ('Subject', 'charge'),
        ('MachineIP', _get_device_ip(info)),
        ('NotifyUrl', '{}/pay/api/{}/renrenpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('SubmitTime', local_now().strftime("%Y%m%d%H%M%S")),
        ('Amt', str(int(pay_amount * 100))),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("renrenpay create: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("renrenpay create rsp data: %s", response.text)
    return {'charge_info': urllib.unquote(_get_str(response.text, 'PayUrl=', '&')).replace('HTTPS://QR.ALIPAY.COM/',
                                                                                           'https://qr.alipay.com/')}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("renrenpay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("renrenpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['OrderID']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('renrenpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['DealStatus'])
    trade_no = data['ThirdSerial']
    total_fee = float(data['Amt']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 0已支付，1未支付，其他失败
    if trade_status == '0':
        _LOGGER.info('renrenpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('TradeType', 'bis.trade.query'),
        ('MerchantID', app_id),
        ('OrderID', str(pay_order.id)),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('renrenpay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info('renrenpay query rsp, %s', response.text)
    if response.status_code == 200:
        mch_id = pay_order.mch_id
        trade_status = _get_str(response.text, 'DealStatus=', '&')
        total_fee = float(_get_str(response.text, 'Amt=', '&')) / 100.0
        trade_no = ''

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '0':
            _LOGGER.info('renrenpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
